package history

import (
	"learn/smart/fetcher"
	"learn/smart/config"
	"fmt"
	"encoding/json"
	"sort"
	"math"
)

type ItemResult struct {
	Status int
	Data   Data
}

type Data struct {
	Count int
	List  []Item
}

type Item struct {
	UserId   int     `json:"user_id"`
	PayMoney float64 `json:"pay_money"`
}

func GetMedianPrice(itemId int) float64 {
	f := fetcher.Fetcher{BaseUrl: config.GetOpenC5gameUrl()}
	path := fmt.Sprintf("/v1/store/item/history?item_id=%d", itemId)

	var price float64
	resp, err := f.Get(path, nil)
	if err != nil {
		return 0
	}
	defer resp.Body.Close()

	contents, err := fetcher.GetContents(resp)
	if err != nil {
		return 0
	}
	var result ItemResult
	json.Unmarshal(contents, &result)

	var priceList []float64
	for _, item := range result.Data.List {
		priceList = append(priceList, item.PayMoney)
	}

	sort.Float64s(priceList)

	if len(priceList) <= 1 {
		return 0
	}
	index := math.Floor(float64(len(priceList) / 2))
	price = priceList[int(index)]

	return price
}
